package com.hcbd.tdwt.ui.common.dialog;

import android.app.Dialog;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.ui.common.adapter.MyBluetoothAdapter;

import com.pangu.bdsdk2021.bluetooth.BluetoothManage;


import java.util.List;

public class BluetoothDialog extends Dialog {
    private Context context;
    private RecyclerView bluetoothRV;
    private List<BluetoothDevice> list;
    private MyBluetoothAdapter myBluetoothAdapter;
    private Button shutDownBtn;
    public BluetoothDialog(Context context) {
        super(context);
        this.context = context;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_bluetooth);
        setCanceledOnTouchOutside(false);
        bluetoothRV=findViewById(R.id.bluetooth_rv);
        shutDownBtn=findViewById(R.id.shutDownBtn);
        shutDownBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BluetoothManage.getInstance().stopDiscovery();
                BluetoothDialog.this.dismiss();
            }
        });
    }
    public void init(List<BluetoothDevice> list){
        this.list=list;
        initBluetoothAdapter();
    }
    public void initBluetoothAdapter(){
        if ( null!=list&& list.size()>0) {
            if (null == myBluetoothAdapter) {
                myBluetoothAdapter = new MyBluetoothAdapter(context, list);
                myBluetoothAdapter.setHasStableIds(true);
            } else {
                myBluetoothAdapter.notifyDataSetChanged(list);
                return;
            }
            GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 1);
            bluetoothRV.setLayoutManager(gridLayoutManager);
            bluetoothRV.setAdapter(myBluetoothAdapter);
            myBluetoothAdapter.setOnItemClickListener(bluetoothDevice -> {
                Toast.makeText(context,"蓝牙连接中", Toast.LENGTH_SHORT).show();
                BluetoothManage.getInstance().connectGatt(bluetoothDevice);
                this.dismiss();

            });
        }
    }
    public static void show(Dialog dialog) {
        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
    }

    public static void shutDown(Dialog dialog) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}